package com.nbstar.film.spider.thread;

import com.nbstar.film.spider.domain.ProxyInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Data
@Slf4j
public class FilmpProxySingleton  {

    private Map<String, ProxyInfo> proxyInfoMap = new HashMap<>();

    public void addProxy(String key, ProxyInfo proxyInfo) {
        proxyInfoMap.put(key, proxyInfo);
    }

    public void deleteProxy(String key) {
        ProxyInfo proxyInfo = proxyInfoMap.get(key);
        proxyInfoMap.remove(key);
        for (Map.Entry<String, ProxyInfo> entry : proxyInfoMap.entrySet()) {
            if (entry.getValue().getProxy().equals(proxyInfo.getProxy())) {//该代理还有spider在使用
                return;
            }
        }

        //该代理已经没人使用了，直接删掉
        log.info("删除代理: {}", proxyInfo);
        com.nbstar.film.spider.thread.ProxyThread.deleteProxyHandler(proxyInfo);
    }

    public ProxyInfo getProxy(String key) {
        ProxyInfo proxy = proxyInfoMap.get(key);
//        if (null == proxy) {
//
//        }

        return proxy;
    }

    public static final FilmpProxySingleton  getInstance () {
        return LazyHolder.LAZY_INNER_SINGLETON;
    }

    private static class LazyHolder {
        public static  FilmpProxySingleton LAZY_INNER_SINGLETON = null;

        static {
            try {
                LAZY_INNER_SINGLETON = new FilmpProxySingleton();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
